package com.ja.openchat.ui.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.MobileContactHomeActivity;
import com.ja.openchat.ui.contact.ContactChooseAdapter;
import com.ja.openchat.ui.contact.GroupContactHomeActivity;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.ja.openchat.views.SideIndexBar;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogPrivacyInfo;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

public class CircleSettingUserActivity extends JaBaseActivity {

    public static void start(Context context, int index){
        Intent intent = new Intent(context,CircleSettingUserActivity.class);
        intent.putExtra("privacyindex",index);
        context.startActivity(intent);
    }

    @BindView(R.id.recyclerView)
    SwipeRecyclerView recyclerView;
    @BindView(R.id.slide)
    SideIndexBar slideBar;
    private ContactChooseAdapter contactChooseAdapter;
    private List<Section> sectionList = new ArrayList<>();
    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }
    private int mBlogPrivacyIndex = BlogPrivacyInfo.DONT_LOOK_ME;
    public List<String> chooseLables = new ArrayList<>();

    @Override
    public void initData() {
        chooseLables.clear();
        chooseLables.add(getString(R.string.group_chat));
        chooseLables.add(getString(R.string.address_book));

        if(getIntent()!=null){
            mBlogPrivacyIndex = getIntent().getIntExtra("privacyindex",BlogPrivacyInfo.DONT_LOOK_ME);
        }
        setTitle(mBlogPrivacyIndex == BlogPrivacyInfo.DONT_LOOK_ME?getString(R.string.do_not_see_my_cirlce):getString(R.string.do_not_see_other_circle));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        contactChooseAdapter = new ContactChooseAdapter(R.layout.adapter_contact_list, R.layout.adapter_section_contact_list, sectionList);
        recyclerView.setAdapter(contactChooseAdapter);
        contactChooseAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        //索引事件
        slideBar.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        load();
    }


    private void load(){
        TelegramManager.getTelegramManager().getCircleAllPrivacy(this, new TgResultBlock<List<BlogPrivacyInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<BlogPrivacyInfo> obj) {
                resetCircleUI(obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }


    private ArrayList<UserInfo> mChooseUserInfos = new ArrayList<>();
    private void resetCircleUI(List<BlogPrivacyInfo> obj){
        mChooseUserInfos.clear();
        List<Long> userIds = null;
        if(!Common.isEmpty(obj)){
            for(BlogPrivacyInfo info:obj){
                if(info.key == mBlogPrivacyIndex){
                    userIds = info.getRule()==null?null:info.getRule().users;
                    break;
                }
            }
        }
        if(userIds==null){
            resetUserInfos(mChooseUserInfos);
            return;
        }
        final int length = userIds.size();
        for(int i = 0;i<length;i++){
            Long userId = userIds.get(i);
            UserInfo userInfo = UserInfo.getUserInfo(userId);
            if(userInfo!=null){
                mChooseUserInfos.add(userInfo);
            }else{
                final int index = i;
                TelegramManager.getTelegramManager().getUserSimpleInfo(userId, new TgResultBlock<UserInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                        mChooseUserInfos.add(obj);
                        if(mChooseUserInfos.size()==length) {
                            resetUserInfos(mChooseUserInfos);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            }
        }
        if(mChooseUserInfos.size()==length){
            resetUserInfos(mChooseUserInfos);
        }

    }


    private void resetUserInfos(List<UserInfo> list){
        sectionList.clear();
        if(Common.isEmpty(list)){
            setTitle(String.format("%s(0)",mBlogPrivacyIndex == BlogPrivacyInfo.DONT_LOOK_ME?getString(R.string.do_not_see_my_cirlce):getString(R.string.do_not_see_other_circle)));
        }else{
            setTitle(String.format("%s(%d)",mBlogPrivacyIndex == BlogPrivacyInfo.DONT_LOOK_ME?getString(R.string.do_not_see_my_cirlce):getString(R.string.do_not_see_other_circle),list.size()));
            if (list.size() > 1) {
                Collections.sort(list, new Comparator<UserInfo>() {
                    @Override
                    public int compare(UserInfo u1, UserInfo u2) {
                        if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                            return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                        }
                        return 0;
                    }
                });
            }
            //生成a-z hash
            Map<String, List<UserInfo>> sectionMap = new HashMap<>();
            for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
                sectionMap.put(azIndex, new ArrayList<>());
            }
            //插入userinfo
            for (UserInfo user : list) {
                if (!StringUtils.isEmpty(user.displayName_full_py)) {
                    if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                        sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                    } else {
                        sectionMap.get("#").add(user);
                    }
                } else {
                    sectionMap.get("#").add(user);
                }
            }
            //ui数据
            for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
                if (sectionMap.get(azIndex).size() > 0) {
                    sectionList.add(new Section(true, new SectionInfo(azIndex)));
                    for (UserInfo user : sectionMap.get(azIndex)) {
                        sectionList.add(new Section(false, user));
                    }
                }
            }
        }
        //刷新页面
        contactChooseAdapter.notifyDataSetChanged();
    }
    private final int REQUEST_USERS = 111;
    private final int REQUEST_GROUPS = 112;
    private final int REQUEST_GROUPS_FOR_MEMBERS = 113;
    private final int REQUEST_REMOVE_USERS = 114;

    @OnClick({R.id.add_btn,R.id.remove_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_btn:
                ChooseListDialog.showChooseListDialog(this, chooseLables, -1,getString(R.string.choose_following_sources) ,new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        if(position == 0){
                            GroupContactHomeActivity.chooseGroups(CircleSettingUserActivity.this, REQUEST_GROUPS, null);
                        }else{
                            startActivityForResult(MobileContactHomeActivity.getActivityForResult(CircleSettingUserActivity.this, 3, mChooseUserInfos), REQUEST_USERS);
                        }
                    }
                });
                break;
            case R.id.remove_btn:
                RemoveCircleSettingUserActivity.startForResult(CircleSettingUserActivity.this,mChooseUserInfos,REQUEST_REMOVE_USERS);
                break;
        }
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_circle_setting_user_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (data.getSerializableExtra("users") != null) {
            Object users = data.getSerializableExtra("users");
            switch (requestCode) {
                case REQUEST_USERS:
                    ArrayList<UserInfo> usersList = (ArrayList<UserInfo>) users;
                    modifyPrivacyUsers(true,usersList);
                    break;
                case REQUEST_GROUPS:
                    ArrayList<ChatInfo> groupsList = (ArrayList<ChatInfo>) users;
                    if(!Common.isEmpty(groupsList)){
                        loadGroupsOfUsers(groupsList);
                    }
                    break;
                case REQUEST_GROUPS_FOR_MEMBERS:
                    ArrayList<UserInfo> usersList1 = (ArrayList<UserInfo>) users;
                    modifyPrivacyUsers(true,usersList1);
                    break;
                case REQUEST_REMOVE_USERS:
                    ArrayList<UserInfo> usersList2 = (ArrayList<UserInfo>) users;
                    modifyPrivacyUsers(false,usersList2);
                    break;
            }
        }
    }

    private void modifyPrivacyUsers(boolean isAdding,List<UserInfo> users){
        if(Common.isEmpty(users)){
            return;
        }
        List<Long> userIds = new ArrayList<>();
        for(UserInfo userInfo:users){
            userIds.add(userInfo.id);
        }
        TelegramManager.getTelegramManager().modifyPrivacyUsers(this, mBlogPrivacyIndex, isAdding, userIds, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                load();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });

    }

    private void loadGroupsOfUsers(List<ChatInfo> chatInfos){
        List<Observable<UserInfo>> observables = new ArrayList<>();
        for(ChatInfo chatInfo:chatInfos){
            observables.add(Observable.create(new ObservableOnSubscribe<GroupMemberInfo>() {

                @Override
                public void subscribe(ObservableEmitter<GroupMemberInfo> emitter) throws Exception {
                    TelegramManager.getTelegramManager().getSuperGroupMembers(CircleSettingUserActivity.this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterContacts", null, 0, 1000, new TgResultBlock<List<GroupMemberInfo>>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                            if(!Common.isEmpty(obj)){
                                for(GroupMemberInfo memberInfo:obj){
                                    emitter.onNext(memberInfo);
                                }
                            }
                            emitter.onComplete();
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            emitter.onComplete();
                        }
                    });
                }
            }).flatMap(new Function<GroupMemberInfo, ObservableSource<UserInfo>>() {
                @Override
                public ObservableSource<UserInfo> apply(GroupMemberInfo groupMemberInfo) throws Exception {
                    return Observable.create(new ObservableOnSubscribe<UserInfo>() {

                        @Override
                        public void subscribe(ObservableEmitter<UserInfo> emitter) throws Exception {
                            final long userId = groupMemberInfo.user_id;
                            UserInfo userInfo = UserInfo.getUserInfo(userId);
                            if(userInfo!=null){
                                emitter.onNext(userInfo);
                                emitter.onComplete();
                            }else{
                                TelegramManager.getTelegramManager().getUserSimpleInfo(userId, new TgResultBlock<UserInfo>() {
                                    @Override
                                    public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                                        emitter.onNext(userInfo);
                                        emitter.onComplete();
                                    }

                                    @Override
                                    public void onTimeout(Map<String, Object> request) {
                                        emitter.onComplete();
                                    }
                                });
                            }
                        }
                    });
                }
            }));
        }
        final HashMap<Long,UserInfo> userInfos = new HashMap<>();
        Observable.merge(observables)
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showProgress();
                    }

                    @Override
                    public void onNext(UserInfo userInfo) {
                        userInfos.put(userInfo.id,userInfo);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        hideProgress();
                        ArrayList<UserInfo> userInfoss = new ArrayList<>(userInfos.values());
                        GroupsMembersChooseActivity.startForResult(CircleSettingUserActivity.this,mChooseUserInfos,userInfoss,REQUEST_GROUPS_FOR_MEMBERS);
                    }
                });
    }

}
